package com.gl.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gl.exception.BusinessException;
import com.gl.mapper.ApplicationMapper;
import com.gl.mapper.UserMapper;
import com.gl.pojo.Result;
import com.gl.pojo.dto.UserPageDto;
import com.gl.pojo.entity.Application;
import com.gl.pojo.entity.User;
import com.gl.pojo.vo.ApplicationPageVo;
import com.gl.pojo.vo.ApplicationVo;
import com.gl.pojo.vo.UserPageVo;
import com.gl.pojo.vo.UserVo;
import com.gl.service.PermissionService;
import com.gl.utils.CurrentHolder;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    ApplicationMapper applicationMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public ApplicationPageVo reviewedPage(UserPageDto userPage) {
        if (userPage.getPage() == null || userPage.getPageSize() == null) {
            throw new BusinessException("分页参数错误");
        }
        PageHelper.startPage(userPage.getPage(), userPage.getPageSize());
        List<Application> list = applicationMapper.selectReviewed(userPage.getUsername());

        PageInfo<Application> result = new PageInfo<>(list);

        // 获取分页结果
        List<ApplicationVo> applicationVoList = new ArrayList<>();
        list.forEach(application -> {
            ApplicationVo applicationVo = new ApplicationVo();
            BeanUtils.copyProperties(application, applicationVo);

            String id = application.getUserId();
            applicationVo.setEmail(userMapper.selectEmailById(id));
            applicationVo.setAvatar(userMapper.selectAvatarById(id));
            applicationVoList.add(applicationVo);
        });
        long total = result.getTotal();

        // 封装
        ApplicationPageVo applicationPageVo = new ApplicationPageVo();
        applicationPageVo.setList(applicationVoList);
        applicationPageVo.setTotal(total);

        return applicationPageVo;
    }

    @Override
    public ApplicationPageVo pendingPage(UserPageDto userPage) {
        if (userPage.getPage() == null || userPage.getPageSize() == null) {
            throw new BusinessException("分页参数错误");
        }
        PageHelper.startPage(userPage.getPage(), userPage.getPageSize());
        List<Application> list = applicationMapper.selectPending(userPage.getUsername());

        PageInfo<Application> result = new PageInfo<>(list);

        List<ApplicationVo> applicationVoList = new ArrayList<>();
        list.forEach(application -> {
            ApplicationVo applicationVo = new ApplicationVo();
            BeanUtils.copyProperties(application, applicationVo);

            String id = application.getUserId();
            applicationVo.setEmail(userMapper.selectEmailById(id));
            applicationVo.setAvatar(userMapper.selectAvatarById(id));
            applicationVoList.add(applicationVo);
        });

        ApplicationPageVo applicationPageVo = new ApplicationPageVo();
        applicationPageVo.setList(applicationVoList);
        applicationPageVo.setTotal(result.getTotal());

        return applicationPageVo;
    }

    @Override
    @Transactional
    public Result applyPermissions(String reason) {
        String id = CurrentHolder.getCurrentId();

        // 新增管理员身份校验
        String userRole = userMapper.selectRoleById(id);
        if ("1".equals(userRole)) {
            return Result.error("您已经是管理员，无需申请");
        }

        if (applicationMapper.existsPendingUserById(id)) {
            return Result.error("申请正在审核中");
        }

        // 获取用户名
        String username = userMapper.selectUsernameByUserId(id);
        if (username == null) {
            return Result.error("用户不存在");
        }

        // 构建申请对象
        Application application = new Application();
        application.setUserId(id);
        application.setReason(reason);
        application.setStatus("pending");  // 数据库有默认值，但显式设置更可靠
        application.setUsername(username);

        // 插入申请记录
        try {
            int affectedRows = applicationMapper.insertApplication(application);
            return affectedRows > 0 ? Result.success() : Result.error("申请提交失败");
        } catch (Exception e) {
            return Result.error("系统异常，请稍后再试");
        }
    }

    @Transactional
    @Override
    public void processApproval(Integer applicationId, String status) {
        // 校验审批状态参数
        if (!"approved".equalsIgnoreCase(status) && !"rejected".equalsIgnoreCase(status)) {
            throw new BusinessException("非法的审批状态");
        }

        // 获取审核人信息
        String currentUserId = CurrentHolder.getCurrentId();
        String reviewerName = userMapper.selectUsernameByUserId(currentUserId);
        if (reviewerName == null) {
            throw new BusinessException("审核人信息获取失败");
        }

        // 执行更新操作
        int affectedRows = applicationMapper.updateApplicationStatus(
                applicationId,
                status.toLowerCase(),
                reviewerName
        );

        // 处理更新结果
        if (affectedRows == 0) {
            Application application = applicationMapper.selectById(applicationId);
            if (application == null) {
                throw new BusinessException("申请记录不存在");
            } else if (!"pending".equals(application.getStatus())) {
                throw new BusinessException("该申请已处理完成");
            } else {
                throw new BusinessException("审批操作失败");
            }
        }

        // 新增角色更新逻辑（仅当审批通过时）
        if ("approved".equalsIgnoreCase(status)) {
            // 获取申请对应的用户ID
            Application application = applicationMapper.selectById(applicationId);
            if (application == null) {
                throw new BusinessException("申请记录不存在");
            }

            // 在角色更新逻辑处添加校验
            User user = userMapper.selectByUserId(application.getUserId());
            if (user == null) {
                throw new BusinessException("关联用户不存在");
            }
            if ("1".equals(user.getRole())) {
                throw new BusinessException("该用户已是管理员");
            }

            // 执行用户角色更新
            int userUpdate = userMapper.updateRoleById(application.getUserId(), "1");
            if (userUpdate == 0) {
                throw new BusinessException("用户角色更新失败");
            }
        }
    }
}
